#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import jsonify, request
from flask_restful import Resource
from utility.odoo_manager import OdooManager  # 操作odoo的单例
from utility.error_code import error_code  # 异常代码
from utility.message_manager import MessageBusManager
from event import event_type
from command import command
import logging,os
from utility import tools
from settings  import DOWN_FILE_DIR
from utility.file_split import split_file
from utility.memcache_manager import MemcacheManager
import pandas as pd

FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT)


class OgttCaseListAPI(Resource):
    """
    糖耐OGTT个案登记本
    :request: post
    :param examDateStart: 检查日期开始
    :param examDateEnd: 检查日期结束
    :param djDateStart: 登记日期开始
    :param djDateEnd: 登记日期结束
    :param daStatus: 档案状态 0 管理中 1 已结案
    #------:param fxbz: 风险标志  --米有------
    :param djrCode: 登记人Code
    :param searchText: 搜索内容
    :param isAsc：排序方向 排序的方向,示例值(asc,desc)
    :param orderByColumn：排序列
    :param pageNum：当前页数
    :param pageSize: 分页大小
    :returns: json string
    """
    def post(self):
        try:
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            is_asc = params.get('isAsc') if params.get('isAsc', False) else 'asc'
            order_by_column = params.get('orderByColumn') if params.get('orderByColumn', False) else 'create_date'
            #  构造排序方式
            order_ = order_by_column+' '+ is_asc
            #  初始化页数,返回数据条数,偏移
            page = int(params.get('pageNum')) if params.get('pageNum', False) else 1
            pagesize = int(params.get('pageSize')) if params.get('pageSize', False) else 10
            offset = page * pagesize - pagesize
            query_ = []
            if params.get('examDateStart'): # 检查日期开始
                query_.append(('jc_date', '>=', params.get('examDateStart'))) 
            if params.get('examDateEnd'): # 检查日期结束
                query_.append(('jc_date', '<=', params.get('examDateEnd')))     
            if params.get('djDateStart'): # 登记日期开始
                query_.append(('dj_date', '>=', params.get('djDateStart')))    
            if params.get('djDateEnd'): # 登记日期结束
                query_.append(('dj_date', '<=', params.get('djDateEnd')))   
            if params.get('djrCode'): # 登记人Code
                query_.append(('dj_r', '=', int(params.get('djrCode'))))
            if params.get('daStatus'): # 档案状态
                query_t_ = []
                query_t_.append(('status', '=', int(params.get('daStatus'))))  #档案状态  
                res_archives = odoo.env['res.archives'].search_read(query_t_,['id'])
                if res_archives:
                    archives_ids = [archives['id']  for archives in res_archives]
                    query_.append(('archives_id', 'in', archives_ids))     
            if params.get('searchText'): # 搜索字符串
                query_t_ = []
                query_t_.append(('mq_xm', 'ilike', int(params.get('searchText'))))  # 孕妇姓名  
                query_t_.append(('mq_sjhm', 'ilike', int(params.get('searchText')))) # 孕妇手机号码  没找到
                query_t_.append(('mq_sfz', 'ilike', int(params.get('searchText')))) # 身份证号
                query_t_.append(('zyh', 'ilike', int(params.get('searchText')))) # 住院号 
                res_archives = odoo.env['res.archives'].search_read(query_t_,['id'])
                if res_archives:
                    archives_ids = [archives['id']  for archives in res_archives]
                    query_.append(('archives_id', 'in', archives_ids))        
            records = odoo.env['inspection.sugar.resistance'].search_read(query_,  offset = offset, limit = pagesize, order = order_)
            data_ = {'dataList': [],'total': 0}   
            data_['total'] = odoo.env['inspection.sugar.resistance'].search_count(query_)  
            if records:
                for  record_ in records:
                    #print (record_)
                    query_ = [('id', '=', int(record_['archives_id'][0]))] 
                    fields = ['mzh','mq_xm','mq_age','mq_sfz','mq_cz_address','mq_sjhm','status']
                    res_archives = odoo.env['res.archives'].search_read(query_,fields)
                    if res_archives:
                        res_archives = res_archives[0]
                        data_tmp = {
                            'bh': record_['id'],
                            'mzh': res_archives['mzh'],
                            'xm': res_archives['mq_xm'],
                            'age': res_archives['mq_age'],
                            'jcyz': '',#record_[''],
                            'idCard': res_archives['mq_sfz'],
                            'addr': res_archives['mq_cz_address'],
                            'phone': res_archives['mq_sjhm'],
                            'scjg': {
                                'xtkf': record_['kg_ptt'],
                                'xt1Hour': record_['yxs_ptt'],
                                'xt2Hour': record_['lxs_ptt'],
                                'fxbz': '',
                                'jcrq': record_['jc_date'],
                                'jcjgName': record_['jc_jg'][-1]
                            },
                            'djrName': record_['dj_r'][-1],
                            'djrq': record_['dj_date'],
                            'daStatus': '管理中' if res_archives['status'] ==0 else '已结束'
                        }
                        data_['dataList'].append(data_tmp)
            return jsonify({'code': 0, 'msg': 'success', 'data': data_})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})


class OgttCaseExportAPI(Resource):
    """
    导出糖耐OGTT个案登记本
    :request: post
    :param examDateStart: 检查日期开始
    :param examDateEnd: 检查日期结束
    :param djDateStart: 登记日期开始
    :param djDateEnd: 登记日期结束
    :param daStatus: 档案状态 0 管理中 1 已结案
    :param fxbz: 风险标志
    :param djrCode: 登记人Code
    :param searchText: 搜索内容
    :param isAsc：排序方向 排序的方向,示例值(asc,desc)
    :param orderByColumn：排序列
    :param pageNum：当前页数
    :param pageSize: 分页大小
    :returns: json string
    """
    def post(self):
        try:
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            #获取UID
            uid = params.get('uid')
            # 防重校验
            cache = MemcacheManager()
            check = cache.get('ogtt_case'+str(uid))
            if check:
                check = check.split(',')
                data_ ={
                        'blob': str(open(check[0], 'rb').read()),
                        'isOver': 0 #0否 1是
                    }
                if len(check)==1:
                    data_['isOver'] = 1   
                    cache.delete('ogtt_case'+str(uid)) 
                else:    
                    check = check[1:]    
                    cache.set('ogtt_case'+str(uid), ','.join(check))
                return {
                    'code': 0,
                    'data': data_,
                    'msg': 'success',
                } 
            is_asc = params.get('isAsc') if params.get('isAsc', False) else 'asc'
            order_by_column = params.get('orderByColumn') if params.get('orderByColumn', False) else 'create_date'
            #  构造排序方式
            order_ = order_by_column+' '+ is_asc
            query_ = []
            if params.get('examDateStart'): # 检查日期开始
                query_.append(('jc_date', '>=', params.get('examDateStart'))) 
            if params.get('examDateEnd'): # 检查日期结束
                query_.append(('jc_date', '<=', params.get('examDateEnd')))     
            if params.get('djDateStart'): # 登记日期开始
                query_.append(('dj_date', '>=', params.get('djDateStart')))    
            if params.get('djDateEnd'): # 登记日期结束
                query_.append(('dj_date', '<=', params.get('djDateEnd')))   
            if params.get('djrCode'): # 登记人Code
                query_.append(('dj_r', '=', int(params.get('djrCode'))))
            if params.get('daStatus'): # 档案状态
                query_t_ = []
                query_t_.append(('status', '=', int(params.get('daStatus'))))  #档案状态  
                res_archives = odoo.env['res.archives'].search_read(query_t_,['id'])
                if res_archives:
                    archives_ids = [archives['id']  for archives in res_archives]
                    query_.append(('archives_id', 'in', archives_ids))     
            if params.get('searchText'): # 搜索字符串
                query_t_ = []
                query_t_.append(('mq_xm', 'ilike', int(params.get('searchText'))))  # 孕妇姓名  
                query_t_.append(('mq_sjhm', 'ilike', int(params.get('searchText')))) # 孕妇手机号码  没找到
                query_t_.append(('mq_sfz', 'ilike', int(params.get('searchText')))) # 身份证号
                query_t_.append(('zyh', 'ilike', int(params.get('searchText')))) # 住院号 
                res_archives = odoo.env['res.archives'].search_read(query_t_,['id'])
                if res_archives:
                    archives_ids = [archives['id']  for archives in res_archives]
                    query_.append(('archives_id', 'in', archives_ids))        
            records = odoo.env['inspection.sugar.resistance'].search_read(query_,  order = order_)
            data_ = []
            if records:
                for  record_ in records:
                    query_ = [('id', '=', int(record_['archives_id'][0]))]
                    fields = ['mzh','mq_xm','mq_age','mq_sfz','mq_cz_address','mq_sjhm','status']
                    res_archives = odoo.env['res.archives'].search_read(query_,fields)
                    if res_archives:
                        res_archives = res_archives[0]
                        data_tmp = {
                            '编号': record_['id'],
                            '门诊号': res_archives['mzh'],
                            '孕妇姓名': res_archives['mq_xm'],
                            '年龄': res_archives['mq_age'],
                            '检查孕周': '',#record_[''],
                            '身份证号': res_archives['mq_sfz'],
                            '常住地址': res_archives['mq_cz_address'],
                            '母亲手机号码': res_archives['mq_sjhm'],
                            '筛查结果-空腹血糖值': record_['kg_ptt'],
                            '筛查结果-1小时血糖': record_['yxs_ptt'],
                            '筛查结果-2小时血糖': record_['lxs_ptt'],
                            '筛查结果-风险标志': '',
                            '筛查结果-检查日期': record_['jc_date'],
                            '筛查结果-检查机构名称': record_['jc_jg'][-1],       
                            '登记人姓名': record_['dj_r'][-1],
                            '登记日期': record_['dj_date'],
                            '档案状态': '管理中' if res_archives['status'] ==0 else '已结束'
                        }
            data_.append(data_tmp)
            res = {'blob':'','isOver':'1'}
            #print (res)
            if data_:
                col_names=[
                    '编号','门诊号','孕妇姓名','年龄','检查孕周','身份证号',
                    '常住地址','母亲手机号码','筛查结果-空腹血糖值','筛查结果-1小时血糖',
                    '筛查结果-2小时血糖','筛查结果-风险标志','筛查结果-检查日期',
                    '筛查结果-检查机构名称','登记人姓名','登记日期','档案状态'
                ]
                df=pd.DataFrame(data_)
                file_path='{}{}-{}-0.xlsx'.format(DOWN_FILE_DIR,'糖耐OGTT个案登记本',uid)
                df.to_excel(file_path,columns=col_names,index=False)
                file_path_n = split_file('{}-{}-0.xlsx'.format('糖耐OGTT个案登记本',uid),col_names)
                #初始文件小于3M
                if file_path == file_path_n[0]:
                    res['blob'] = str(open(file_path, 'rb').read())
                    os.remove(file_path)
                else:
                    res['blob'] = str(open(file_path_n[0], 'rb').read()) 
                    os.remove(file_path_n[0])
                    res['isOver'] = '0'
                    #文件大于3M
                    req_flag = ','.join(file_path_n[1:])
                    #文件名保存到缓存里
                    cache.set('ogtt_case'+str(uid), req_flag)
            #print (res)
            return jsonify({'code': 0, 'msg': 'success', 'data': res})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

